package com.jiawa.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.business.domain.Req.TrainStationQueryReq;
import com.jiawa.train.business.domain.Req.TrainStationSaveReq;
import com.jiawa.train.business.domain.TrainStation;
import com.jiawa.train.business.domain.TrainStationExample;
import com.jiawa.train.business.domain.resp.TrainStationQueryResp;
import com.jiawa.train.business.mapper.TrainStationMapper;
import com.jiawa.train.common.resp.CommonResp;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TrainStationService {
    @Autowired
    private TrainStationMapper trainStationMapper;


    public PageResp<TrainStationQueryResp> queryList(@Valid TrainStationQueryReq req) {
        TrainStationExample example = new TrainStationExample();
        PageHelper.startPage(req.getPage(), req.getSize());
        List<TrainStation> trainStationList = trainStationMapper.selectByExample(example);

        List<TrainStationQueryResp> queryRespList = BeanUtil.copyToList(trainStationList, TrainStationQueryResp.class);

        PageInfo<TrainStation> pageInfo = new PageInfo<>(trainStationList);

        PageResp<TrainStationQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(queryRespList);
        return pageResp;
    }

    public void save(@Valid TrainStationSaveReq req) {
        TrainStation trainStation = new TrainStation();
        BeanUtils.copyProperties(req, trainStation);

        if(ObjectUtil.isNull(trainStation.getId())){
            trainStation.setId(SnowUtil.getSnowflakeNextId());
            trainStation.setCreateTime(new Date());
            trainStation.setUpdateTime(new Date());
            trainStationMapper.insert(trainStation);
        }else {
            trainStation.setUpdateTime(new Date());
            trainStationMapper.updateByPrimaryKeySelective(trainStation);
        }
    }

    public void delete(Long id) {
        trainStationMapper.deleteByPrimaryKey(id);
    }

    public List<TrainStation> selectByTrainCode(String trainCode) {

        TrainStationExample example = new TrainStationExample();
        example.setOrderByClause("train_code desc");
        example.createCriteria().andTrainCodeEqualTo(trainCode);
        List<TrainStation> trainStationList = trainStationMapper.selectByExample(example);
        return trainStationList;
    }
}
